<template>
  <b-container class="my-5 animated fadeIn">
    <b-row>
      <b-col cols="12">
        <b-form @submit="onSubmit">
          <b-form-group label="主题" label-for="input_title" description="这里输入主题，不要超过50个字符">
            <b-form-input id="input_title" v-model="form.Title" required placeholder="请输入主题"></b-form-input>
          </b-form-group>

          <b-form-group label="板块" label-for="input_category" description="选择发布的板块">
            <b-form-select v-model="form.selected" :options="options" required></b-form-select>
          </b-form-group>

          <b-form-group label="内容" label-for="input_text" description="这里输入内容">
            <mavon-editor class="md" v-model="form.Text"></mavon-editor>
          </b-form-group>
          <b-form-group>
            <b-button to="/" variant="light">取消</b-button>&nbsp;
            <b-button type="submit" variant="dark">提交</b-button>
          </b-form-group>
        </b-form>
      </b-col>
    </b-row>
  </b-container>
</template>

<script>
import axios from "axios";

export default {
  name: "Editor",
  data() {
    return {
      options: [],
      form: {
        Title: "",
        Text: "",
        selected: "",
        UserID: this.$store.state.UserID,
      }
    };
  },
  created() {
    axios
        .get("/dev_api/categories")
        .then(response => {
          if (response.data.code === 200) {
            console.log("板块信息：", response.data.data)
            response.data.data.forEach(data => {
              this.options.push({value: data.id, text: data.name})
            })
          } else {
            console.log("板块获取失败")
          }
        })
  },
  methods: {
    onSubmit(evt) {
      evt.preventDefault();
      console.log(JSON.stringify(this.form))
      this.axios({
        method: "post",
        url: "/dev_api/topics",
        data: {
          title: this.form.Title,
          categoryId: this.form.selected,
          content: this.form.Text,
          tags: []
        },
        headers: {
          "Authorization": this.$store.state.token
        }
      })
          .then(response => {
            if (response.data.code === 200) {
              alert("发表成功")
              this.$router.push("/")
            } else {
              this.$bvToast.toast(response.data.msg, {
                title: "消息",
                variant: "danger",
                autoHideDelay: 1000,
                solid: true
              });
            }
          })
          .catch(error => {
            alert("发送失败\n", error)
          })
    }
  }
};
</script>